<template>
  <a-spin :spinning="confirmLoading">
    <div class="p-4">
      <a-form ref="formRef" class="antd-modal-form" :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }">
        <a-row>
          <a-col :span="24">
            <a-form-item label="渠道">
              <a-input v-model:value="formData.channel" placeholder="请输入渠道"></a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <BasicTable @register="registerTable" @edit-change="onEditChange">
        <template #action="{ record, column }">
          <TableAction :actions="createActions(record, column)" />
        </template>
      </BasicTable>
      <a-button type="primary" @click="addRules">添加渠道规则</a-button>
    </div>
  </a-spin>
</template>
<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps } from 'vue';
  import { BasicTable, TableAction, ActionItem, EditRecordRow } from '/@/components/Table';
  import { saveOrUpdate } from '../ChannelSettlementConfig.api';
  import { cloneDeep } from 'lodash-es';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { Form } from 'ant-design-vue';
  import { formTableColumns } from '../ChannelSettlementConfig.data';

  const props = defineProps({
    formData: { type: Object, default: () => {} },
  });
  const useForm = Form.useForm;
  const formData = reactive<Record<string, any>>({
    id: '',
    channel: '',
  });
  //表单验证
  const validatorRules = {
    channel: [{ required: true, message: '请输入渠道!' }],
  };
  const confirmLoading = ref<boolean>(false);
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });
  const emit = defineEmits(['register', 'ok']);
  const { createMessage } = useMessage();
  const currentEditKeyRef = ref('');
  const dataSource = [
    {
      key: '1',
      name: '胡歌',
      age: 32,
      address: '朝阳区林萃路1号',
    },
    {
      key: '2',
      name: '刘诗诗',
      age: 32,
      address: '昌平区白沙路1号',
    },
  ];
  const { tableContext } = useListPage({
    designScope: 'basic-table-demo',
    tableProps: {
      title: '配置结算规则',
      columns: formTableColumns,
      dataSource,
      showIndexColumn: false,
      useSearchForm: false,
      actionColumn: {
        width: 160,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
      },
    },
  });

  //BasicTable绑定注册
  const [registerTable, { updateTableDataRecord, insertTableDataRecord, setTableData }] = tableContext;

  // 演示不刷新表格直接更新内部数据。
  // 注意：updateTableDataRecord要求表格的rowKey属性为string并且存在于每一行的record的keys中
  // const result = updateTableDataRecord(values.id, values);

  function handleEdit(record: EditRecordRow) {
    currentEditKeyRef.value = record.key;
    record.onEdit?.(true);
  }

  function handleCancel(record: EditRecordRow) {
    currentEditKeyRef.value = '';
    record.onEdit?.(false, false);
  }
  function addRules() {}
  async function handleSave(record: EditRecordRow) {
    // 校验
    createMessage.loading({ content: '正在保存...', duration: 0, key: 'saving' });
    const valid = await record.onValid?.();
    if (valid) {
      try {
        const data = cloneDeep(record.editValueRefs);
        console.log(data);
        //TODO 此处将数据提交给服务器保存
        // ...
        // 保存之后提交编辑状态
        const pass = await record.onEdit?.(false, true);
        if (pass) {
          currentEditKeyRef.value = '';
        }
        createMessage.success({ content: '数据已保存', key: 'saving' });
      } catch (error) {
        createMessage.error({ content: '保存失败', key: 'saving' });
      }
    } else {
      createMessage.error({ content: '请填写正确的数据', key: 'saving' });
    }
  }

  function createActions(record: EditRecordRow): ActionItem[] {
    if (!record.editable) {
      return [
        {
          label: '编辑',
          disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
          onClick: handleEdit.bind(null, record),
        },
      ];
    }
    return [
      {
        label: '保存',
        onClick: handleSave.bind(null, record),
      },
      {
        label: '取消',
        popConfirm: {
          title: '是否取消编辑',
          confirm: handleCancel.bind(null, record),
        },
      },
    ];
  }

  function onEditChange({ column, value, record }) {
    // 本例
    if (column.dataIndex === 'id') {
      record.editValueRefs.name4.value = `${value}`;
    }
    console.log(column, value, record);
  }

  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData, record);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>
